package com.guanmi.ethereum.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;

import com.guanmi.ethereum.configure.EthConfigure;

@Component
public class EthereumBlockListener implements ApplicationListener<ContextRefreshedEvent> {

	private static final Logger log = LoggerFactory.getLogger(EthereumBlockListener.class);

	@Autowired
	private EthConfigure  ethConfigure;
	public void onApplicationEvent(ContextRefreshedEvent evt) {

		if (evt.getApplicationContext().getParent() != null) {
			return;
		}

		// 获取 数据库配置的地址和端口
		Web3j web3j = Web3j.build(new HttpService(ethConfigure.getNodeUrl()));
		web3j.blockFlowable(false).subscribe(block -> {
			// 这里就可以根据新增区块来处理转入转出确认数的逻辑了
			log.info("新增区块:{}", block.getBlock().getNumber());
		});
	}
}
